<template>
  <div class="app-container">

    <el-row :gutter="20">
      <!--类别数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="deptName"
              placeholder="请输入产品类别名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="goodsTreeList"
              :props="{ label: 'name', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="goodsTreeListRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleTreeNodeClick"
          />
        </div>
      </el-col>


      <!--部门数据-->
      <el-col :span="20" :xs="24">

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="产品编码" prop="parentCode">
            <el-input v-model="queryParams.parentCode" placeholder="请输入产品编码" clearable
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入产品名称"
                      clearable @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="更新时间" style="width: 308px">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['md:goods:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['md:goods:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['md:goods:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['md:goods:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="产品编码" align="center" prop="parentCode"/>
          <el-table-column label="产品名称" align="center" prop="name"/>
          <el-table-column label="规格型号" align="center" prop="specification"/>
          <el-table-column label="计量单位" align="center" prop="measureUnit">
            <template #default="scope">
              <dict-tag :options="wms_goods_measure_unit" :value="scope.row.measureUnit"/>
            </template>
          </el-table-column>
          <el-table-column label="包装单位" align="center" prop="packingUnit">
            <template #default="scope">
              <dict-tag :options="wms_goods_measure_unit" :value="scope.row.packingUnit"/>
            </template>
          </el-table-column>
          <el-table-column label="包装数量" align="center" prop="packingQuantity"/>
          <!--      <el-table-column label="商城商品" align="center" prop="isShop"/>-->
          <!--      <el-table-column label="是否物料" align="center" prop="isMaterial"/>-->
          <!--      <el-table-column label="是否生产品" align="center" prop="isProduct"/>-->
          <!--      <el-table-column label="是否库存" align="center" prop="isStock"/>-->
          <!--      <el-table-column label="是否销售" align="center" prop="isCrm"/>-->
          <el-table-column label="是否启用" align="center" prop="enableFlag">
            <template #default="scope">
              <dict-tag :options="sys_state" :value="scope.row.enableFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="类型ID" align="center" prop="categoryId"/>
          <el-table-column label="类型" align="center" prop="categoryName"/>
          <el-table-column label="备注" align="center" prop="remark"/>
          <!--      <el-table-column label="创建者" align="center" prop="createBy"/>-->
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--      <el-table-column label="更新者" align="center" prop="updateBy"/>-->
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="180" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['md:goods:edit']">
                修改产品
              </el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdateGoodsLine(scope.row)"
                         v-hasPermi="['md:goods:edit']">
                产品数据明细
              </el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['md:goods:remove']">删除产品
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改产品对话框 -->
        <el-dialog :title="title" v-model="open" width="950px" append-to-body>
          <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="8">
                <el-form-item label="产品编码" prop="name">
                  <el-input v-model="form.parentCode" disabled placeholder="产品编码会自动生成"/>
                </el-form-item>
                <el-form-item label="计量单位" prop="measureUnit">
                  <el-select v-model="form.measureUnit" placeholder="请选择计量单位">
                    <el-option
                        v-for="dict in wms_goods_measure_unit"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="类别" prop="categoryId">
                  <el-tree-select
                      v-model="form.categoryId" :data="goodsTreeList"
                      value-key="id" check-strictly :render-after-expand="false"
                      :props="{ value: 'id', label: 'name', children: 'children' }"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入产品名称"/>
                </el-form-item>
                <el-form-item label="包装单位" prop="packingUnit">
                  <el-select v-model="form.packingUnit" placeholder="请选择包装单位">
                    <el-option
                        v-for="dict in wms_goods_measure_unit" :key="dict.value"
                        :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否启用" prop="enableFlag">
                  <el-switch v-model="form.enableFlag" active-text="启用"
                             active-value="0" inactive-text="停用" inactive-value="1"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="规格型号" prop="specification">
                  <el-input v-model="form.specification" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="包装数量" prop="packingQuantity">
                  <el-input v-model="form.packingQuantity" placeholder="请输入包装数量"/>
                </el-form-item>
                <el-form-item label="是否库存" prop="isStock">
                  <el-switch v-model="form.isStock" active-text="启用"
                             active-value="0" inactive-text="停用" inactive-value="1"/>
                </el-form-item>

              </el-col>
            </el-row>

            <!--        <el-form-item label="商城商品" prop="isShop">-->
            <!--          <el-input v-model="form.isShop" placeholder="请输入商城商品"/>-->
            <!--        </el-form-item>-->
            <!--        <el-form-item label="是否物料" prop="isMaterial">-->
            <!--          <el-input v-model="form.isMaterial" placeholder="请输入是否物料"/>-->
            <!--        </el-form-item>-->
            <!--        <el-form-item label="是否生产品" prop="isProduct">-->
            <!--          <el-input v-model="form.isProduct" placeholder="请输入是否生产品"/>-->
            <!--        </el-form-item>-->
            <!--        <el-form-item label="是否销售模块可用" prop="isCrm">-->
            <!--          <el-input v-model="form.isCrm" placeholder="请输入是否销售模块可用"/>-->
            <!--        </el-form-item>-->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 产品数据明细 添加或修改产品对话框 -->
        <el-dialog :title="goodsLine.title" v-model="goodsLine.open" width="1000px" append-to-body>
          <el-row :gutter="10" class="mb8">

            <el-form ref="attrRef" :inline="true" label-width="68px">
              <el-form-item label="属性" prop="attrNameList">
                <el-input style="width: 350px" v-model="queryParams.attributeValue"
                          placeholder="多属性用竖线隔开：红色|橙色|黄色|绿色"></el-input>
              </el-form-item>
            </el-form>
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAddMdGoodsLines">属性添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAddMdGoodsLine">新增一行</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" icon="Check" @click="saveLines">保存</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="Delete" @click="handleDeleteMdGoodsLine">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" icon="Close" @click="goodsLine.open = false">关闭</el-button>
            </el-col>
          </el-row>

          <el-table :data="goodsLine.list" :row-class-name="rowMdGoodsLineIndex"
                    @selection-change="handleMdGoodsLineSelectionChange" ref="mdGoodsLine">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="是否启用" prop="enableFlag" width="150">
              <template #default="scope">
                <el-switch v-model="scope.row.enableFlag"
                           active-text="启用"
                           active-value="0"
                           inactive-text="停用"
                           inactive-value="1"/>
              </template>
            </el-table-column>
            <el-table-column label="价格(￥)" prop="price" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.price" placeholder="请输入价格"/>
              </template>
            </el-table-column>
            <!--        *******************************-->
            <el-table-column label="产品属性" prop="attrValue" width="300">
              <template #default="scope">
                <el-input v-model="scope.row.attrValue" placeholder="产品属性"/>
              </template>
            </el-table-column>
            <!--        <el-table-column label="产品属性" prop="attrValue" width="300">-->
            <!--          <template #default="scope">-->
            <!--            <el-input v-model="scope.row.attrValue" placeholder="产品属性"/>-->
            <!--          </template>-->
            <!--        </el-table-column>-->
            <!--        *******************************-->
            <el-table-column label="是否设置安全库存" prop="safeStockFlag" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.safeStockFlag" placeholder="请输入"/>
              </template>
            </el-table-column>
            <el-table-column label="最低库存量" prop="minStock" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.minStock" placeholder="请输入"/>
              </template>
            </el-table-column>
            <el-table-column label="最大库存量" prop="maxStock" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.maxStock" placeholder="请输入"/>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注"/>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>


      </el-col>
    </el-row>

  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  listGoodsLines,
  saveMdGoodsLines,
  delLine
} from "@/api/md/goods";
import {listTree, getTree, delTree, addTree, updateTree} from "@/api/md/tree";
import {addMdValue, getMaterialAttributeValueListById, listMdValue, updateMdValue} from "@/api/md/mdValue";

const {proxy} = getCurrentInstance();

const goodsList = ref([]);
const goodsTreeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMdGoodsLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);
const {sys_state, wms_goods_measure_unit} = proxy.useDict('sys_state', 'wms_goods_measure_unit');

const data = reactive({
  form: {
    categoryId: 1,
  },
  queryParams: {
    categoryId: 1,
    pageNum: 1,
    pageSize: 10,
    parentCode: null,
    name: null,
    specification: null,
    updateTime: null,
    packingUnit: null,
    measureUnit: null,
    enableFlag: null,
    attributeValue: null
  },
  rules: {},
});

const {queryParams, form, rules} = toRefs(data);

/*** 订单明细参数 */
const goodsLine = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "订单明细",
  //表格数据
  list: [],
  //打开窗口的编码
  parentCode:null,
  // 多属性数据
  attrList: []
});

/** 查询产品列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
  });
  loading.value = false;
}

function getGoodsTree(categoryId) {
  listTree({parentId: categoryId}).then(response => {
    goodsTreeList.value = proxy.handleTree(response.data, "id", "parentId");
  });
}

/** 节点单击事件 */
function handleTreeNodeClick(data) {
  queryParams.value.categoryId = data.id;
  handleQuery();
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    parentCode: null,
    name: null,
    specification: null,
    packingUnit: null,
    measureUnit: null,
    packingQuantity: null,
    isShop: null,
    isMaterial: null,
    isProduct: null,
    isStock: "0",
    isCrm: null,
    enableFlag: "0",
    categoryId: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    tenantId: null
  };
  // mdGoodsLineList.value = [];
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.parentCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _parentCode = row.parentCode || ids.value
  getGoods(_parentCode).then(response => {
    form.value = response.data;
    // mdGoodsLineList.value = response.data.mdGoodsLineList;
    open.value = true;
    title.value = "修改产品";
  });
}

/** 提交按钮 */
function submitForm() {
  debugger
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      // form.value.mdGoodsLineList = mdGoodsLineList.value;
      if (form.value.parentCode != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _parentCodes = row.parentCode || ids.value;
  proxy.$modal.confirm('是否确认删除产品编号为"' + _parentCodes + '"的数据项？').then(function () {
    return delGoods(_parentCodes);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 物料产品序号 */
function rowMdGoodsLineIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}


/** 多属性对话框操作按钮操作 */
function handleUpdateGoodsLine(row) {
  goodsLine.open = true;
  goodsLine.title = "产品名称:" + row.name + " 产品编码:" + row.parentCode;
  goodsLine.parentCode = row.parentCode;
  goodsLine.list = [];
  getGoodsLines(row.parentCode);
}

/** 查询物多属性数据 */
function getGoodsLines(parentCode) {
  listGoodsLines({parentCode: parentCode}).then(response => {
    goodsLine.list = response.rows;
  })
}

/** 物料产品多属性添加按钮操作 */
function handleAddMdGoodsLines() {
  debugger;
  let attrList = queryParams.value.attributeValue.split("|");
  let attrTableList = [];
  let i = 0;
  let j = 0;

  if (goodsLine.list.length == 0){
    let row = {attrValue:""};
    handleAddMdGoodsLine(row);
  }
  while (goodsLine.list.length>i){
    attrTableList[i] = goodsLine.list[i].attrValue;
    i++;
  }

  i = 0;
  while (attrList.length>i){
    j = 0;
    while (attrTableList.length>j){
      if (i == 0){
        if (attrTableList[j]==""){
          goodsLine.list[j].attrValue = attrList[i];
        }else {
          goodsLine.list[j].attrValue = attrTableList[j]+"|"+attrList[i];
        }
      }else{
        if (attrTableList[j]==""){
          handleAddMdGoodsLine({attrValue:attrList[i]});
        }else {
          handleAddMdGoodsLine({attrValue:attrTableList[j]+"|"+attrList[i]});
        }
      }
      j++;
    }
    i++;
  }
  queryParams.value.attributeValue ='';
}

/** 物料产品添加按钮操作 */
function handleAddMdGoodsLine(row) {
  const time = new Date();
  let obj = {};
  obj.price = "";
  obj.attrValue = row.attrValue;
  obj.enableFlag = "0";
  obj.safeStockFlag = "";
  obj.minStock = "";
  obj.maxStock = "";
  obj.remark = "";
  obj.createBy = "";
  obj.createTime = "";
  obj.updateBy = "";
  obj.updateTime = "";
  obj.tenantId = "";
  obj.parentCode = goodsLine.parentCode;
  obj.code = "line" + time.getTime() + 1;
  goodsLine.list.push(obj);
}

/** 新增按钮操作 */
function saveLines() {
  const mdGoodsLines = goodsLine.list
  for (let i = 0; i < mdGoodsLines.length; i++) {
    saveMdGoodsLines(mdGoodsLines[i]).then(response => {
      proxy.$modal.msgSuccess("新增成功");
    });
    proxy.$modal.msgError("新增失败");
  }
}

/** 物料产品删除按钮操作 */
function handleDeleteMdGoodsLine() {
  if (checkedMdGoodsLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物料产品数据");
  } else {
    debugger
    const mdGoodsLines = goodsLine.list
    const checkedMdGoodsLines = checkedMdGoodsLine.value;
    goodsLine.list = mdGoodsLines.filter(function (item) {
      debugger
      if (!checkedMdGoodsLines.indexOf(item.index)) {
        debugger
        delLineByCode(item.code)
      }
      return checkedMdGoodsLines.indexOf(item.index) == -1
    });
  }
}

/** 删除按钮操作 */
function delLineByCode(code) {
  proxy.$modal.confirm("确认删除").then(function () {
    return delLine(code);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 复选框选中数据 */
function handleMdGoodsLineSelectionChange(selection) {
  checkedMdGoodsLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('md/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}

function initPage() {
  getGoodsTree(queryParams.value.categoryId);
}

initPage();
getList();

</script>
